package com.changgou.system.filter;

import com.changgou.system.confing.FilterListProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;

/**
 * @Author: HuangFu
 * @Date: 2020/1/16 16:03
 * @Description: Ip过滤器
 */
@Component
public class MyIpGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private FilterListProperties filterListProperties;

    /**
     * 业务处理
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取IP黑名单
        String[] ips = filterListProperties.getIps();
        if(ips !=null){
            InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
            //System.out.println("ip:"+remoteAddress.getHostName());
            for (String ip : ips) {
                //校验是否是黑名单ip
                if(ip.equals(remoteAddress .getHostName())){
                    //设置响应状态未授权 401
                    exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                    //设置响应完结
                    return exchange.getResponse().setComplete();
                }
            }
        }
        return chain.filter(exchange);
    }

    /**
     * 过滤器执行优先级 越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
